package seeders

import (
	"goravel/app/models"

	"github.com/goravel/framework/facades"
)

type UserSeeder struct {
}

// Signature The name and signature of the seeder.
func (s *UserSeeder) Signature() string {
	return "UserSeeder"
}

// Run executes the seeder logic.
func (s *UserSeeder) Run() error {
	// 定义多个用户数据
	users := []map[string]any{
		{
			"username": "root001",
			"password": "123456",
			"is_root":  1,
			"status":   1,
			//"tenant_id": 1,
		},
	}

	// 遍历用户数据
	for _, userData := range users {
		username := userData["username"].(string)

		// 检查用户名是否已存在
		var exists bool
		if err := facades.Orm().Query().Model(&models.User{}).Where("username", username).Exists(&exists); err != nil {
			facades.Log().Error("Failed to check user existence: ", err)
			return err
		}

		// 如果用户不存在，则创建用户
		if !exists {
			password, _ := facades.Hash().Make(userData["password"].(string)) // 生成密码哈希

			// 将 int 类型显式转换为 uint8
			isRoot := uint8(userData["is_root"].(int))
			status := uint8(userData["status"].(int))
			//tenantId := uint(userData["tenant_id"].(int))

			user := models.User{
				Username: username,
				Password: password,
				IsRoot:   isRoot,
				Status:   status,
				//TenantID: tenantId,
			}

			if err := facades.Orm().Query().Create(&user); err != nil {
				facades.Log().Error("Failed to create user: ", err)
				return err
			}

			facades.Log().Info("Generated user: ", user.Username)
		} else {
			facades.Log().Info("User already exists: ", username)
		}
	}

	return nil
}
